package com.ruiysoft.security.service;

import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.common.util.SerializationUtils;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.code.RandomValueAuthorizationCodeServices;
import org.springframework.util.Assert;

/**
 * Created by 化增光 on 2018/10/28.
 */
public class CustomAuthorizationCodeService extends RandomValueAuthorizationCodeServices {

    private static final String AUTH_CODE_KEY = "auth_code";

    private RedisConnectionFactory redisConnectionFactory;

    public CustomAuthorizationCodeService(RedisConnectionFactory redisConnectionFactory) {
        Assert.notNull(redisConnectionFactory, "RedisConnectionFactory required");
        this.redisConnectionFactory = redisConnectionFactory;
    }
    @Override
    protected void store(String code, OAuth2Authentication authentication) {
        RedisConnection conn = getConnection();
        try {
            conn.hSet(AUTH_CODE_KEY.getBytes("utf-8"), code.getBytes("utf-8"),
                    SerializationUtils.serialize(authentication));
        } catch (Exception e) {
            //logger.error("保存authentication code 失败", e);
        } finally {
            conn.close();
        }
    }

    @Override
    protected OAuth2Authentication remove(String code) {
        RedisConnection conn = getConnection();
        try {
            OAuth2Authentication authentication = null;
            try {
                authentication = SerializationUtils
                        .deserialize(conn.hGet(AUTH_CODE_KEY.getBytes("utf-8"), code.getBytes("utf-8")));
            } catch (Exception e) {
                //logger.error("查询authentication code 失败",e);
                return null;
            }
            if (null != authentication) {
                conn.hDel(AUTH_CODE_KEY.getBytes("utf-8"), code.getBytes("utf-8"));
            }
            return authentication;
        } catch (Exception e) {
            //logger.error("删除authentication code 失败",e);
            return null;
        } finally {
            conn.close();
        }
    }
    private RedisConnection getConnection() {
        return redisConnectionFactory.getConnection();
    }
}
